﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YaAppoint.Common;
using YaAppoint.Response;

namespace YaAppoint.TextTemplates
{
    /// <summary>
    /// 文本模板服务
    /// </summary>
    [RemoteService(isEnabled: false)]
    public class TextTemplateAppService(ICommonAppService commonAppService,
                                        AsyncQueryableExecuter queryableExecuter,
                                        IMapper mapper,
                                        IRepository<TextTemplate,Guid> templateRepositroy):ApplicationService,ITextTemplateAppService,ITransientDependency
    {
        private readonly ICommonAppService _commonAppService = commonAppService;
        private readonly IRepository<TextTemplate, Guid> _templateRepositroy = templateRepositroy;
        private readonly AsyncQueryableExecuter _queryableExecuter = queryableExecuter;
        private readonly IMapper _mapper = mapper;

        /// <summary>
        /// 获取模板类型选项
        /// </summary>
        public BackJson GetTypeOptions()
        {
            var values = Enum.GetValues(typeof(TemplateType));
            List<Dictionary<string,object>> data = new List<Dictionary<string,object>>(); 
            foreach (Enum item in values)
            {
                data.Add(new Dictionary<string, object> {
                    { "value",Convert.ToInt32(item)},
                    { "label",_commonAppService.GetEnumValueDescription(item)}
                });
            }
            return new BackJson
            {
                code = 0,
                data = data
            };
        }


        /// <summary>
        /// 获取模板列表
        /// </summary>
        public async Task<BackJson> GetTemplateList(string? filterName, TemplateType? type)
        {
            var query = await _templateRepositroy.GetQueryableAsync();
            if (!string.IsNullOrEmpty(filterName) && filterName!="null")
            {
                query = query.Where(t => t.Name.Contains(filterName) || t.TypeName.Contains(filterName) || t.Interface.Contains(filterName));
            }
            if (type != null)
            {
                query = query.Where(t => t.Type == type);
            }
            query = query.OrderBy(t => t.Type).ThenBy(t=>t.Interface).ThenBy(t => t.CreationTime);
            var list = await _queryableExecuter.ToListAsync(query);
            return new BackJson
            {
                code = 0,
                data = _mapper.Map<List<TextTemplate>,List<TextTemplateDto>>(list)
            };
        }

        /// <summary>
        /// 获取模板详情
        /// </summary>
        public async Task<BackJson> GetDetail(Guid id)
        {
            var template = await _templateRepositroy.FirstOrDefaultAsync(t => t.Id == id);
            if (template == null)
            {
                throw new BusinessException(CustomErrorCodes.TextTemplateNotExist);
            }
            return new BackJson
            {
                code = 0,
                data = _mapper.Map<TextTemplate, TextTemplateDto>(template)
            };
        }

        /// <summary>
        /// 删除
        /// </summary>
        public async Task<BackJson> Delete(Guid id)
        {
            var template = await _templateRepositroy.FirstOrDefaultAsync(t => t.Id == id);
            if (template != null)
            {
                await _templateRepositroy.DeleteAsync(id);
            }
           
            return new BackJson
            {
                code=0,
                msg="删除成功"
            };
        }

        /// <summary>
        /// 提交新建
        /// </summary>
        public async Task<BackJson> SubmitCreate(CreateTextTemplateDto dto)
        {
            var entity = _mapper.Map<CreateTextTemplateDto, TextTemplate>(dto);
            await _templateRepositroy.InsertAsync(entity);
            return new BackJson
            {
                code = 0,
                msg="保存成功"
            };
        }

        /// <summary>
        /// 提交编辑
        /// </summary>
        public async Task<BackJson> SubmitEdit(TextTemplateDto dto)
        {
            var entity = await _templateRepositroy.FirstOrDefaultAsync(t => t.Id == dto.Id);
            if (entity == null)
            {
                throw new BusinessException(CustomErrorCodes.TextTemplateNotExist);
            }
            _mapper.Map<TextTemplateDto, TextTemplate>(dto, entity);
            await _templateRepositroy.UpdateAsync(entity);
            return new BackJson
            {
                code = 0,
                msg = "保存成功"
            };
        }

    }
}
